package cn.kgc.rbac.controller;

import cn.hutool.captcha.LineCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author: mosin
 * @version: v1.0  2023/1/30
 */
@Controller
@RequestMapping("captcha")
public class CaptchaController {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @RequestMapping("getCaptcha")
    public void getCaptcha(HttpServletResponse response, HttpSession session){

        //生成验证码
        LineCaptcha lineCaptcha = new LineCaptcha(110, 50, 4, 5);
        String code = lineCaptcha.getCode();
        //存储验证码  session  redis  设置时效性
        redisTemplate.opsForValue().set(session.getId(), code, 1, TimeUnit.MINUTES);

        try {
            ServletOutputStream outputStream = response.getOutputStream();
            lineCaptcha.write(outputStream);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
